package com.ruike.alisurface.serialport;

import com.voodoo.lib_logcat.L;

import org.greenrobot.eventbus.EventBus;

public class QrCodeUtils {

    public static void initListener() {
        StringBuilder builder = new StringBuilder();
        Ttys1Utils.getInstance().setOnSerialPortResultDataListener(new Ttys1Utils.OnSerialPortResultDataListener() {
            @Override
            public void onDataReceived(String resultDataStr, byte[] resultBytes) {
                if (resultBytes.length > 6) {
                    if (resultBytes[0] == (byte) 0x02 && resultBytes[1] == (byte) 0x00) {
                        if (resultBytes[2] == (byte) 0x00) {
                            //设置成功
                            L.i("信息返回成功");
                            return;
                        }
                    }
                    try {
                        String data = resultDataStr.replaceAll(" ", "");
                        builder.append(data);
                        if (data.endsWith("0D0A")) {
                            String codedata = builder.toString().replaceAll("0D0A", "");
                            String doctor_bar_code = convertHexToString(codedata);
                            L.i("16进制转换为ASCII ", codedata, doctor_bar_code);
                            EventBus.getDefault().post(new MsgEventBus("扫码code", doctor_bar_code));
                            builder.delete(0, builder.length());
                        }
                    } catch (Exception e) {
                        L.i("Exception  " + e.getMessage());
                    }
                }
            }
        });
    }

    // 命令模式操作扫码器
    public static void sendCommandCode() {
        Ttys1Utils.getInstance().SendPort("7E000801000201ABCD");
    }

    // 恢复出厂设置
    public static void sendCommandRestore() {
        Ttys1Utils.getInstance().SendPort("7E0009010000FFC038");
    }

    /**
     * 16进制转换为ASCII
     *
     * @param hex
     * @return
     */
    public static String convertHexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {
            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);
            temp.append(decimal);
        }
        return sb.toString();
    }
}
